import { action, computed, makeObservable, observable, runInAction } from 'mobx'
import { createContext, useContext } from 'react'
class TodoStore {
  list = [{taskName: 'asdasd', completed: false}]
  constructor() {
    makeObservable(this, {
      list: observable,
      total: computed,
      todoAdd: action.bound,
      toggle: action.bound
    })
    this.loadTodos()
  }

  todoAdd(taskName) {
    this.list.push({
      taskName,
      completed: false
    })
  }

  get total() {
    return this.list.filter(todo => !todo.completed).length
  }

  toggle(todo) {
    const item = this.list.find(item => item.taskName === todo.taskName)
    item.completed = !item.completed
  }
  loadTodos() {
    runInAction(() => {
      setTimeout(() => {
        this.list.push({taskName: 'sadasdasdasdasd', completed: false})
      });
    })
  }
}

const TodoContext = createContext()
const TodoStoreProvider = ({ store, children }) => {
  return <TodoContext.Provider value={store}>{children}</TodoContext.Provider>
}
const useTodoStore = () => useContext(TodoContext)
export {
  TodoStoreProvider,
  useTodoStore,
  TodoStore
}
